<template>
  <el-form ref="form" label-width="120px">
    <el-form-item label="模块名称">
      <el-input v-model="form.func_module_name" placeholder="名称，如：人员相关函数"></el-input>
    </el-form-item>
    <el-form-item label="模块包名">
      <el-input v-model="form.func_module_code" placeholder="编码，如：adminModule，命名请使用全英文，云函数的文件名"></el-input>
    </el-form-item>
    <el-form-item
      class="form-item-center"
      label=""
      label-width="0px">
      <el-button
        size="default"
        type="primary"
                 @click="handleSubmitCreateGroup"> 提交 </el-button>
      <el-button size="default" @click="handleCancel"> 取消 </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import _ from 'lodash';
import {api} from "@jzl/api";
import { $jui} from '@jzl/utils'
import { isPlatform, isApp, isGlobal, isTask, isFuncModule } from "./common.js";

const props = defineProps({
  currentData: Object,
  app: Object
});

const emit = defineEmits(['close']);

const DEFAULT_FORM = {
  func_module_code: '',
  func_module_name: '',
  app_id: -1,
  type: null
};

const loading = ref(false);
const actionType = ref('view'); // createModule | createMenu | edit | view
const form = ref(_.cloneDeep(DEFAULT_FORM));
const rules = {
  func_module_code: [
    { required: true, message: '请输入函数模块编码', trigger: 'blur' }
  ],
  func_module_name: [
    { required: true, message: '请输入函数模块名称', trigger: 'blur' }
  ]
};

const init = () => {
  let formValue = null;
  if (props.currentData && props.currentData.func_module_id) {
    formValue = _.cloneDeep(props.currentData);
  } else {
    let appId = _.get(props.currentData, 'id');
    let type = 3;

    if (isPlatform(props.currentData)) {
      type = 1;
    } else if (isGlobal(props.currentData)) {
      type = 2;
    } else if (isApp(props.currentData)) {
      type = 3;
    }

    formValue = _.defaults({
      func_module_code: '',
      func_module_name: '',
      app_id: appId > 0 ? appId : -1,
      type
    }, DEFAULT_FORM);
  }

  form.value = formValue;
};

const handleSubmitCreateGroup = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'func_module_id');
  let ret = null;

  if (id) {
    ret = await api.func.moduleUpdate(id, data);
  } else {
    ret = await api.func.moduleCreate(data);
  }

  let tid = _.get(form.value, 'tid') || `M_${_.get(ret, 'func_module_id')}`;

  loading.value = false;

  if (ret) {
    $jui.toast('操作成功！');
    handleCancel(tid);
  }
};

const handleCancel = (tid) => {
  emit('close', tid);
};

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, { deep: true });

watch(() => props.app, () => {
  init();
}, { deep: true });

watch(() => actionType.value, () => {
  init();
});
</script>
